import store from '@/store'

function selectTargets(targets, count) {
	const aliveTargets = targets.filter(t => t.hp > 0);
	const selectedTargets = [];
	while (selectedTargets.length < count && aliveTargets.length > 0) {
		const randomIndex = Math.floor(Math.random() * aliveTargets.length);
		selectedTargets.push(aliveTargets[randomIndex]);
		aliveTargets.splice(randomIndex, 1);
	}
	return selectedTargets;
}


module.exports = (_skill = {}) => {
	
	let {skill_id=1,count=1,times=1,type='normal',release='player_attack'} = _skill;

	let player = store.state.player;
	
	let attack_target = selectTargets(getApp().globalData.monsters,count);
	
	let data_skill = getApp().$data_skill.find(item => item.id == skill_id);
	
	let damage = 0;
	
	let atk = getApp().$common.rnd(player.attr.min_atk,player.attr.max_atk);
	
	let base_damage = atk + (atk * player.attr.add_dmg / 1000);
	
	for(let i=0;i<attack_target.length;i++){
		
		for(let j=0;j<times;j++){
			setTimeout(() => {
				
				switch (skill_id){
					case 1: //普通攻击
						damage = base_damage
						break;
					case 2: //刺杀剑术
						damage = base_damage * 1.3
						break
					case 3: //月华剑术
						damage = base_damage * 1.7
						break
					case 4: //烈火剑法
						damage = base_damage * 3.0
						break
					default:
						damage = 0
						break;
				}

				if(Math.random() <= player.attr.crit / 1000){
					type = 'crit';
					damage = (damage * (1.5 + player.attr.crit_dmg / 1000))
				}
				
				uni.$emit(release, {
					type,
					skill : skill_id,
					damage : Math.round(damage),
					target : attack_target[i].uuid
				})
			},j*150)
		}
		
	}
	
}